package com.tao.controller;

import com.tao.mapper.ProductMapper;
import com.tao.pojo.dto.ProductDTO;
import com.tao.pojo.dto.ProductUpdateDTO;
import com.tao.pojo.entity.Product;
import com.tao.pojo.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Value("${dirPath}")
    private String dirPath;

    @Autowired
    ProductMapper productMapper;

    @RequestMapping("/insert")
    public void insert(@RequestBody ProductDTO productDTO){
        System.out.println("productDTO = " + productDTO);
        Product p = new Product();
        BeanUtils.copyProperties(productDTO,p);
        p.setCreated(new Date());
        p.setViewCount(0);
        productMapper.insert(p);
    }

    @RequestMapping("/select/admin")
    public List<ProductAdminVO> selectAdmin(){
        return productMapper.selectAdmin();
    }

    @RequestMapping("/delete")
    public void delete(int id){
        String url = productMapper.selectUrlById(id);
        new File(dirPath+url).delete();
        productMapper.deleteById(id);
    }
    @RequestMapping("/selectById/update")
    public ProductUpdateVO selectByIdUpdate(int id){
        return productMapper.selectByIdUpdate(id);
    }

    @RequestMapping("/update")
    public void update(@RequestBody ProductUpdateDTO productUpdateDTO){
        System.out.println("productUpdateDTO = " + productUpdateDTO);
        productMapper.update(productUpdateDTO);
    }
    @RequestMapping("/select/top")
    public List<ProductTopVO> selectTop(){
        return productMapper.selectTop();
    }

    @RequestMapping("/select/index")
    public List<ProductIndexVO> selectIndex(){
        return productMapper.selectIndex();
    }

    @RequestMapping("/selectById/detail")
    public ProductDetailVO selectByIdDetail(int id, HttpSession session){
        String info = (String) session.getAttribute("view"+id);
        if (info==null){
            productMapper.updateViewCount(id);
            session.setAttribute("view"+id,"isVisited");
        }
        return productMapper.selectByIdDetail(id);
    }
    @RequestMapping("/selectByCid")
    public List<ProductIndexVO> selectByCid(int id){
        return productMapper.selectByCid(id);
    }
    @RequestMapping("/selectByWd")
    public List<ProductIndexVO> selectByWd(String wd){
        return productMapper.selectByWd(wd);
    }
}
